<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <style>
        #model-answer div {
            white-space: pre-wrap; /* 保证文本能够换行 */
        }
        #user-input {
            width: 100%; /* 设置输入框宽度为父容器的100% */
            max-width: 600px; /* 最大宽度为600px */
            box-sizing: border-box; /* 确保内边距和边框包含在宽度内 */
            padding: 10px; /* 增加一些内边距使输入框看起来更舒适 */
            font-size: 16px; /* 设置字体大小 */
            line-height: 1.5; /* 设置行高 */
            border-radius: 4px; /* 圆角边框 */
            border: 1px solid #ccc; /* 边框颜色 */
        }
        #chat-form {
            margin-bottom: 20px; /* 表单底部外边距 */
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }
    </style>
    <title>Form Submission Example</title>
</head>
<body>
<h2>智能AI</h2>
<!-- 表单元素 -->
<form id="chat-form">
    <!-- 增加了input的样式和属性 -->
    <input type="text" id="user-input" name="user_input" placeholder="Type your question here..." maxlength="500" size="50">
    <button type="submit">Send</button>
</form>

<!-- 用于显示用户提问和模型回答的区域 -->
<div id="user-question"></div>
<div id="model-answer"></div>

<script>
document.getElementById('chat-form').addEventListener('submit', async function(event) {
    event.preventDefault(); // 阻止默认的表单提交行为

    const userInput = document.getElementById('user-input').value.trim();
    if (!userInput) return;

    // 显示用户的问题
    document.getElementById('user-question').textContent = userInput;
    document.getElementById('model-answer').textContent = ''; // 清除之前的回答

    // 创建FormData对象并添加表单数据
    const formData = new FormData();
    formData.append('user_input', userInput);

    try {
        const response = await fetch('/', { // 假设您的FastAPI服务运行在根路径上
            method: 'POST',
            body: formData, // 使用FormData对象作为请求体
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let done = false;

        while (!done) {
            const { value, done: doneReading } = await reader.read();
            done = doneReading;
            const chunk = decoder.decode(value, { stream: true });
            document.getElementById('model-answer').innerHTML += `<span>${chunk}</span>`;
        }
    } catch (error) {
        console.error('Error:', error);
    }
});
</script>
</body>
</html>